package com.tomcov.client.activities;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.tomcov.client.ClientFactory;
import com.tomcov.client.place.LicencePlace;
import com.tomcov.client.place.MapPlace;
import com.tomcov.client.service.UserServiceAsync;
import com.tomcov.client.view.WelcomView;
import com.tomcov.shared.UserInfo;

public class WelcomActivity extends AbstractActivity implements WelcomView.Presenter{

	private ClientFactory clientFactory;

	/**
	 * Instantiates a new welcom activity.
	 *
	 * @param clientFactory the client factory
	 */
	public WelcomActivity(ClientFactory clientFactory){
		this.clientFactory = clientFactory;	
	}

	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		WelcomView welcomView = clientFactory.getWelcomView();
		welcomView.getLoginButton().addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				WelcomView welcomView = clientFactory.getWelcomView();
				welcomView.getLoginButton().setVisible(false);
				login();
				welcomView.getLoginButton().setVisible(true);

			}
		});
		welcomView.getCreateUserButton().addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				goTo(new LicencePlace(null));

			}
		});
		welcomView.setPresenter(this);
		panel.setWidget(welcomView.asWidget());
	}

	@Override
	public void goTo(Place place) {
		clientFactory.getPlaceController().goTo(place);
	}

	public void login(){
		WelcomView welcomView = clientFactory.getWelcomView();
		UserServiceAsync USA = clientFactory.getUSA();
		/*byte[] passenc = new byte[0];
		try{
			Cryptage crypt=new Cryptage();
			passenc=crypt.Encrypt(welcomView.getPassword());
		}
		catch(Exception e){
			
		}
		System.out.println(passenc.toString());*/
		
		USA.login(welcomView.getUserName(),welcomView.getPassword(),new AsyncCallback<UserInfo>(){
			public void onFailure(Throwable error) {
				GWT.log(error.getMessage());
				WelcomView welcomView = clientFactory.getWelcomView();
				Window.alert("User "+welcomView.getUserName()+" not loged in...");
			}
			public void onSuccess(UserInfo user) {
				if (user==null){
					WelcomView welcomView = clientFactory.getWelcomView();
					Window.alert("User "+welcomView.getUserName()+" doesn't exist");}
				else{
					//WelcomView welcomView = clientFactory.getWelcomView();
					//Window.alert("User "+welcomView.getUserName()+" log");
					goTo(new MapPlace(null));
				}
			}

		});
	}

}
